package cn.yanhu.kuwanapp.home.fragment

import android.content.Context
import android.graphics.Color
import android.util.DisplayMetrics
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.viewpager2.widget.ViewPager2
import cn.woochen.comlib.BaseFragment
import cn.woochen.comlib.adapter.GridSpacingItemDecoration
import cn.woochen.comlib.adapter.OnItemClickListener
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.ext.dp
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.bean.response.RespCarouselBean
import cn.yanhu.kuwanapp.bean.response.RespUserInfoBean
import cn.yanhu.kuwanapp.common.activity.CommonWebviewActivity
import cn.yanhu.kuwanapp.databinding.FragmentHomeBinding
import cn.yanhu.kuwanapp.earn.activity.GameSearchActivity
import cn.yanhu.kuwanapp.home.MainViewModel
import cn.yanhu.kuwanapp.home.adapter.HomeRewardAdapter
import cn.yanhu.kuwanapp.home.adapter.HomeTopMenuAdapter
import cn.yanhu.kuwanapp.home.adapter.ViewPageAdapter
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.NavigatorHelper
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.helper.ViewPagerHelper
import cn.yanhu.kuwanapp.welfare.VideoActivity
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView
import java.util.concurrent.TimeUnit

/**
 *
 * 类描述：首页
 * @author：woochen
 * create at：2021/7/27 10:38 PM
 */
class HomeFragment : BaseFragment<FragmentHomeBinding, MainViewModel>(), OnSingleClickListener {

    private val mUserViewModel by viewModels<UserViewModel>()
    private val mActivityUserViewModel by viewModels<UserViewModel>({requireActivity()})

    private val mHomeTopMenuDatas by lazy {
        mutableListOf<RespUserInfoBean.Icon>()
    }

    private val mHomeTopMenuAdapter by lazy {
        HomeTopMenuAdapter(mHomeTopMenuDatas)
    }

    private val mHomeRewardDatas by lazy {
        mutableListOf<RespCarouselBean.InnerBean>()
    }
    private val mHomeRewardAdapter by lazy {
        HomeRewardAdapter(mHomeRewardDatas)
    }

    override fun setContentView(): Int = R.layout.fragment_home

    override fun initData() {
        initWidgets()
        requestData()
    }

    override fun initListener() {
        mBinding.tvSign.setOnSingleClickListener(this)
        mBinding.tvMore.setOnSingleClickListener(this)
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //用户信息
        mUserViewModel.userInfoInfo.observe(this, Observer { it ->
            parseState(it, {
                mBinding.userInfo = it
                mBinding.rvTopMenu.isVisible = !it.icons.isNullOrEmpty()
                mHomeTopMenuDatas.clear()
                mHomeTopMenuDatas.addAll(it.icons)
                mHomeTopMenuAdapter.notifyDataSetChanged()
            })
        })
        mActivityUserViewModel.userInfoInfo.observe(this, Observer { it ->
            parseState(it, {
                mBinding.userInfo = it
                mBinding.rvTopMenu.isVisible = !it.icons.isNullOrEmpty()
                mHomeTopMenuDatas.clear()
                mHomeTopMenuDatas.addAll(it.icons)
                mHomeTopMenuAdapter.notifyDataSetChanged()
            })
        })
        //奖励信息轮播
        mViewModel.carouselInfo.observe(this, Observer { it ->
            parseState(it, {
                mBinding.rewardInfo = it
                mHomeRewardDatas.clear()
                mHomeRewardDatas.addAll(it.list)
                mHomeRewardAdapter.notifyDataSetChanged()
                mBinding.rvReward.postDelayed({
                    (mBinding.rvReward.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                        Integer.MAX_VALUE / 2,
                        0
                    )
                    startAuto()
                }, 500)

            })
        })
    }

    private val titles = mutableListOf("推荐", "快赚", "益智", "手游", "最新")
    private val fragments = mutableListOf<Fragment>()
    inner class PageChangeCallback : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
           /* val view = fragments[position].view
            view?.let {
                it.postDelayed({
                    updatePagerHeightForChild(view, mBinding.viewpager)
                },0)
            }*/
        }
    }

    private val mPageChangeCallback by lazy {
        PageChangeCallback()
    }

    private fun updatePagerHeightForChild(view: View, pager: ViewPager2) {
        view.post {
            val wMeasureSpec =
                View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
            val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(wMeasureSpec, hMeasureSpec)
            if (pager.layoutParams.height != view.measuredHeight) {
                pager.layoutParams = (pager.layoutParams)
                    .also { lp ->
                        lp.height = view.measuredHeight
                    }
            }
        }
    }

    private fun initTab() {
        if (fragments.size > 0) return
        for (index in titles.indices) {
            fragments.add(GameListFragment.newInstance(index))
        }
        val commonNavigator = CommonNavigator(mContext)
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val clipPagerTitleView = ClipPagerTitleView(context)
                clipPagerTitleView.text = titles[index]
                clipPagerTitleView.textSize = 14f.dp
                clipPagerTitleView.textColor = Color.parseColor("#666666")
                clipPagerTitleView.clipColor = Color.parseColor("#333333")
                clipPagerTitleView.setOnClickListener { mBinding.viewpager.currentItem = index }
                return clipPagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.roundRadius = 2f.dp
                indicator.lineHeight = 3f.dp
                indicator.xOffset = 13f.dp
                indicator.setColors(Color.parseColor("#FF6E28"))
                return indicator
            }
        }
        commonNavigator.isAdjustMode = false
        mBinding.magicIndicator.navigator = commonNavigator
        mBinding.viewpager.adapter = ViewPageAdapter(this, fragments)
        mBinding.viewpager.offscreenPageLimit = titles.size
        ViewPagerHelper.bind2(mBinding.magicIndicator, mBinding.viewpager)
        mBinding.viewpager.registerOnPageChangeCallback(mPageChangeCallback)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopAuto()
        mBinding.viewpager.unregisterOnPageChangeCallback(mPageChangeCallback)
    }

    private val mSmoothScroll by lazy {
        object : LinearSmoothScroller(mContext) {
            override fun getVerticalSnapPreference(): Int {
                return SNAP_TO_START
            }

            override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
                return 3f / (displayMetrics?.density ?: 1f)
            }

        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        logcom("onHiddenChanged:${hidden}")
        if (hidden){
            stopAuto()
        }else{
            startAuto()
        }
    }

   /* override fun onStart() {
        super.onStart()
        startAuto()
    }

    override fun onStop() {
        super.onStop()
        stopAuto()
    }
*/
    private var mAutoTask: Disposable? = null

    private fun startAuto() {
        if (mAutoTask != null && mAutoTask?.isDisposed == false) {
            mAutoTask?.dispose()
        }
        if (mHomeRewardDatas.isNotEmpty()) {
            mAutoTask = Observable.interval(1, 2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe {
                    //定位到指定项如果该项可以置顶就将其置顶显示
                    val linearLayoutManager = mBinding.rvReward.layoutManager as LinearLayoutManager
                    mSmoothScroll.targetPosition =
                        linearLayoutManager.findFirstVisibleItemPosition() - 1
                    linearLayoutManager.startSmoothScroll(mSmoothScroll)
                }
        }

    }

    private fun stopAuto() {
        if (mAutoTask != null && (mAutoTask?.isDisposed != false)) {
            mAutoTask?.dispose()
            mAutoTask = null
        }
    }

    private fun initWidgets() {
        mBinding.llNormalView.isVisible = !Constants.isExamine
        mBinding.rvTopMenu.run {
            layoutManager = GridLayoutManager(mContext, 4)
            addItemDecoration(GridSpacingItemDecoration(4, 15f.dp.toInt(), false))
            adapter = mHomeTopMenuAdapter
            mHomeTopMenuAdapter.mItemClickListener = OnItemClickListener {
                val icon = mHomeTopMenuDatas[it]
                NavigatorHelper.toPage(mContext,icon.linkUrl)
            }
        }
        mBinding.rvReward.run {
            adapter = mHomeRewardAdapter
            mHomeRewardAdapter.mOperateListener = object : HomeRewardAdapter.OperateListener {
                override fun click(position: Int) {
                    val innerBean = mHomeRewardDatas[position]
                    NavigatorHelper.toCpl(mContext,innerBean.gameId)
//                    NavigatorHelper.toCpl(mContext,innerBean.detailUrl)
                }
            }
        }
        initTab()
    }

    override fun requestData() {
        mViewModel.carousel()
    }

    override fun onStart() {
        super.onStart()
        if (!isHidden){
            getUserInfo()
        }
    }

    private fun getUserInfo() {
        mUserViewModel.userInfo("0")
    }


    fun refreshData() {
        requestData()
    }

    companion object {
        fun newInstance() = HomeFragment()
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.tvSign -> {//签到
                NavigatorHelper.toPage(mContext,"KU_WAN_PAGE_INDEX/?Page=4")
            }
            mBinding.tvMore -> {//更多游戏
                NavigatorHelper.toPage(mContext,"KU_WAN_PAGE_INDEX/?Page=2")
            }
        }
    }
}